package com.htfyun;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

import com.htfyun.fragment.App.AppFragment;
import com.htfyun.fragment.library.LibraryMainFragment;
import com.htfyun.fragment.postil.HtfyunPWFragment;
import com.htfyun.fragment.read.ReadFragment;
import com.htfyun.fragment.base.BaseMainFragment;
import com.htfyun.fragment.settings.SettingsMainFragment;
import com.htfyun.fragment.settings.SettingsWifiFragment;
import com.htfyun.utils.DebugLog;
import com.htfyun.view.BottomBar;
import com.htfyun.view.BottomBarTab;
import com.kongqw.permissionslibrary.PermissionsManager;

import org.androidannotations.annotations.KeyDown;
import org.geometerplus.zlibrary.ui.android.R;

import me.yokeyword.fragmentation.SupportActivity;
import me.yokeyword.fragmentation.SupportFragment;

/**
 * Created by sst on 2017/10/31.
 */

public class MainActivity extends SupportActivity implements BaseMainFragment.OnBackToFirstListener {

    public static final int FIRST = 0;
    public static final int SECOND = 1;
    public static final int THIRD = 2;
    public static final int FOURTH = 3;
//    public static final int FIVE = 4;
    public static final int MAX = 4;

    private Context mContext;

    private SupportFragment[] mFragments = new SupportFragment[MAX];

    private BottomBar mBottomBar;

    private View layoutParent;
    private View fl_container;

    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private final int GET_WIFI_LIST_REQUEST_CODE = 0;
    private PermissionsManager mPermissionsManager;

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        mContext = this;
        Thread.setDefaultUncaughtExceptionHandler(new org.geometerplus.zlibrary.ui.android.library.UncaughtExceptionHandler(this));

//        ScanLocalBookManager.INSTANCE.init(this);

        // 动态权限管理器
        mPermissionsManager = new PermissionsManager(this) {
            @Override
            public void authorized(int requestCode) {
                // 6.0 以上系统授权通过
                if (GET_WIFI_LIST_REQUEST_CODE == requestCode) {

                }
            }

            @Override
            public void noAuthorization(int requestCode, String[] lacksPermissions) {
                // 6.0 以上系统授权失败
            }

            @Override
            public void ignore() {
                // 6.0 以下系统 获取WIFI列表
            }
        };
        // 请求WIFI列表
        mPermissionsManager.checkPermissions(GET_WIFI_LIST_REQUEST_CODE, PERMISSIONS);


        ScanInstalledAppManager.INSTANCE.init(this);

        setContentView(R.layout.htfyun_activity_main);

        layoutParent = findViewById(R.id.layoutParent);
        layoutParent.setEinkUpdateMode(View.EINK_DATA_MODE_DEFAULT, View.EINK_SHOW_MODE_GL);
        layoutParent.setAppEinkMode(View.EINK_SHOW_MODE_GC, View.EINK_GATE_DEFAULT);

        fl_container = findViewById(R.id.fl_container);
        fl_container.setEinkUpdateMode(View.EINK_DATA_MODE_DEFAULT,  View.EINK_SHOW_MODE_GC);

        SupportFragment firstFragment = findFragment(ReadFragment.class);
        if (firstFragment == null) {
            mFragments[FIRST] = ReadFragment.newInstance();
            mFragments[SECOND] = LibraryMainFragment.newInstance();

            mFragments[THIRD] = HtfyunPWFragment.newInstance();
            mFragments[FOURTH] = AppFragment.newInstance();
//            mFragments[FIVE] = SettingsMainFragment.newInstance();

            loadMultipleRootFragment(R.id.fl_container, FIRST,
                    mFragments[FIRST],
                    mFragments[SECOND],
                    mFragments[THIRD],
                    mFragments[FOURTH]
//                    mFragments[FIVE]
                    );

        } else {
            // 这里库已经做了Fragment恢复,所有不需要额外的处理了, 不会出现重叠问题

            // 这里我们需要拿到mFragments的引用
            mFragments[FIRST] = firstFragment;
            mFragments[SECOND] = findFragment(LibraryMainFragment.class);
            mFragments[THIRD] = findFragment(HtfyunPWFragment.class);
            mFragments[FOURTH] = findFragment(AppFragment.class);
//            mFragments[FIVE] = findFragment(SettingsMainFragment.class);
        }

        initView();

        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;  // 屏幕宽度（像素）
        int height = metric.heightPixels;  // 屏幕高度（像素）
        float density = metric.density;  // 屏幕密度（0.75 / 1.0 / 1.5）
        int densityDpi = metric.densityDpi;  // 屏幕密度DPI（120 / 160 / 240）

        DebugLog.e("densityDpi = " + densityDpi + ", density = " + density);

    }

    @Override
    protected void onResume() {
        super.onResume();
        DebugLog.e("main resume");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        ScanInstalledAppManager.INSTANCE.deInit(this);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        DebugLog.e("intent = " + intent);
    }

    private void initView() {
        mBottomBar = (BottomBar) findViewById(R.id.bottomBar);

        mBottomBar.addItem(new BottomBarTab(this, R.drawable.selector_read, ""))//"阅读"))
                .addItem(new BottomBarTab(this,R.drawable.selector_library, ""))//"书库"))
                .addItem(new BottomBarTab(this, R.drawable.selector_note, ""))//"笔记"))
                .addItem(new BottomBarTab(this, R.drawable.selector_application, "")//"应用")
//                .addItem(new BottomBarTab(this, R.drawable.selector_settings, "")//"设置"))
                );

        mBottomBar.setOnTabSelectedListener(new BottomBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position, int prePosition) {
                showHideFragment(mFragments[position], mFragments[prePosition]);
            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {
                final SupportFragment currentFragment = mFragments[position];
                int count = currentFragment.getChildFragmentManager().getBackStackEntryCount();


            }
        });
    }

    @Override
    public void onBackPressedSupport() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            pop();
        } else {
            ActivityCompat.finishAfterTransition(this);
        }
    }

    private Toast toastF10;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        DebugLog.e("event = " + event.getAction() + ", keyCode = " + keyCode);

        if (keyCode == KeyEvent.KEYCODE_HOME && (event.getAction() == KeyEvent.ACTION_DOWN)) {

            if (mBottomBar.getCurrentItemPosition() != 0) {
                mBottomBar.setCurrentItem(0);
            }

            layoutParent.forceEinkFullUpdate();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_F10) {
            if (toastF10 == null) {
                toastF10 = Toast.makeText(mContext, null, Toast.LENGTH_SHORT);
            }
            toastF10.cancel();
            toastF10.setText("Hall " + ((event.getAction() == KeyEvent.ACTION_DOWN) ? "on" : "off"));
            toastF10.show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackToFirstFragment() {
        mBottomBar.setCurrentItem(0);
    }

    /**
     * Android 6.0 权限校验
     *
     * @param requestCode  requestCode
     * @param permissions  permissions
     * @param grantResults grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 复查权限
        mPermissionsManager.recheckPermissions(requestCode, permissions, grantResults);
    }
}
